package com.zf.yichat.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.zf.yichat.dto.StTicketDto;
import com.zf.yichat.mapper.StOfficialTicketMapper;
import com.zf.yichat.mapper.StUserTicketMapper;
import com.zf.yichat.mapper.UserMapper;
import com.zf.yichat.model.StOfficialTicket;
import com.zf.yichat.model.StUserTicket;
import com.zf.yichat.model.SysDict;
import com.zf.yichat.model.User;
import com.zf.yichat.service.SysDictService;
import com.zf.yichat.service.TicketsService;
import com.zf.yichat.utils.common.FsConst;
import com.zf.yichat.utils.response.FsResponse;
import com.zf.yichat.utils.response.FsResponseGen;
import com.zf.yichat.vo.DictKey;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class TicketsServiceImpl implements TicketsService {

    @Autowired
    private SysDictService sysDictService;

    @Resource
    private StUserTicketMapper userTicketMapper;
    @Resource
    private StOfficialTicketMapper officialTicketMapper;
    @Resource
    private UserMapper userMapper;

    @Override
    public int giveUserTickets(Long userId) {

        Example example = new Example(StUserTicket.class);
        example.createCriteria().andEqualTo("userId", userId).andEqualTo("ticketType", StUserTicket.TYPE_REGISTER);
        List<StUserTicket> list = userTicketMapper.selectByExample(example);
        if (null != list && list.size() > 0) {
            return 0;
        }

        StUserTicket ticket = new StUserTicket();
        ticket.setTicketType(StUserTicket.TYPE_REGISTER);
        ticket.setStatus(StUserTicket.STATUS_ACTIVATION_NO);
        ticket.setUserId(userId);
        ticket.setCreateTime(new Date());
        ticket.setTicketCode(IdUtil.simpleUUID());

        return  userTicketMapper.insertSelective(ticket);
    }

    @Override
    public List<StUserTicket> queryUserTickets(Long userId, Integer status) {

        Example example = new Example(StUserTicket.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId", userId);
        if (null != status) {
            criteria.andEqualTo("status", status);
        }
        List<StUserTicket> list = userTicketMapper.selectByExample(example);
        return list;
    }

    @Override
    public FsResponse activateUserTickets(Long adminUserId, String ticketCode, Long userId) {

        User activationUser = userMapper.queryUserByParam("", adminUserId);
        // 判断激活用户是否门票管理员
        String admins = Optional.ofNullable(sysDictService.selectOne(DictKey.sys_dict_ticket_admin)).map(SysDict::getMemo).orElse(null);
        if(admins == null){
            return FsResponseGen.failMsg("无激活权限");
        }
        if(!admins.contains(adminUserId.toString())){
            return FsResponseGen.failMsg("无激活权限");
        }

        // 判断该门票是否已激活
        StUserTicket userTicket = userTicketMapper.queryUserTicketByCode(userId, ticketCode);
        if (null == userTicket) {
            return FsResponseGen.failMsg("门票不存在！");
        }

        Integer status = userTicket.getStatus();
        if (StUserTicket.STATUS_ACTIVATION_YES.equals(status)) {
            return FsResponseGen.failMsg("门票已激活，无需重复激活！");
        }

        Long ticketUserId = userTicket.getUserId();
        User ticketUser = userMapper.queryUserByParam("", ticketUserId);
        if (null == ticketUser) {
            return FsResponseGen.failMsg("门票持有者不存在！");
        }

        String remark = activationUser.getNick() + "于" + DateUtil.today() + "激活" + ticketUser.getNick() + "的门票";

        StUserTicket ticket = new StUserTicket();
        ticket.setId(userTicket.getId());
        ticket.setStatus(StUserTicket.STATUS_ACTIVATION_YES);
        ticket.setActivationTime(new Date());
        ticket.setActivationUser(activationUser.getNick());
        ticket.setRemark(remark);
        userTicketMapper.updateByPrimaryKeySelective(ticket);
        return FsResponseGen.successMsg(remark);
    }

    @Override
    public FsResponse officialInvitationTickets(Long userId, String ticketCode) {

        // 查询官方配置的有效门票
        Example example = new Example(StOfficialTicket.class);
        example.createCriteria().andEqualTo("status", FsConst.Status.EFFECT).andEqualTo("ticketCode", ticketCode);
        StOfficialTicket officialTicket = officialTicketMapper.selectOneByExample(example);
        if (null == officialTicket) {
            return FsResponseGen.failMsg("抱歉，该门票码已失效！");
        }

        Integer status = officialTicket.getStatus();
        if (FsConst.Status.INVALID == status) {
            return FsResponseGen.failMsg("抱歉，该门票码已失效！");
        }

        // 根据后台配置的有效天数和有效次数来判断本次邀请是否生效
        Example exampleUserTicket = new Example(StUserTicket.class);
        exampleUserTicket.createCriteria().andEqualTo("ticketCode", ticketCode).andEqualTo("ticketType", StUserTicket.TYPE_OFFICIAL);
        List<StUserTicket> userTickets = userTicketMapper.selectByExample(exampleUserTicket);

        Integer scanCount = officialTicket.getScanCount();
        Integer scannedCount = userTickets.size();

        // 已扫描次数大于等于可扫描次数
        if (scannedCount >= scanCount){
            StOfficialTicket ticket = new StOfficialTicket();
            ticket.setId(officialTicket.getId());
            ticket.setStatus(FsConst.Status.INVALID);
            officialTicketMapper.updateByPrimaryKeySelective(ticket);
            return FsResponseGen.failMsg("抱歉，该门票码已失效，【可用次数不足】！");
        }

        // 日期是否失效

        // 有效天数
        Integer validDays = officialTicket.getValidDays();
        // 开始有效时间
        Date startDate = officialTicket.getStartDate();
        Date effectiveTime = DateUtil.offsetDay(startDate, validDays);

        Date nowDate = DateUtil.date();
        if (nowDate.after(effectiveTime)) {
            StOfficialTicket ticket = new StOfficialTicket();
            ticket.setId(officialTicket.getId());
            ticket.setStatus(FsConst.Status.INVALID);
            officialTicketMapper.updateByPrimaryKeySelective(ticket);
            return FsResponseGen.failMsg("抱歉，该门票码已失效，【日期过期】！");
        }

        // 判断用户是否已领取门票
        StUserTicket ticket = userTicketMapper.queryUserTicketByCode(userId, ticketCode);
        if (null != ticket) {
            return FsResponseGen.failMsg("您已领取门票！");
        }


        // 新增官方类型 用户门票
        StUserTicket userTicket = new StUserTicket();
        userTicket.setTicketType(StUserTicket.TYPE_OFFICIAL);
        userTicket.setStatus(StUserTicket.STATUS_ACTIVATION_NO);
        userTicket.setUserId(userId);
        userTicket.setCreateTime(new Date());
        userTicket.setTicketCode(ticketCode);
        return FsResponseGen.successData(userTicketMapper.insertSelective(userTicket));
    }

    @Override
    public List<StTicketDto> queryUserScanCode(String ticketCode) {
        Example example = new Example(StUserTicket.class);
        example.createCriteria().andEqualTo("ticketCode", ticketCode).andEqualTo("ticketType", StUserTicket.TYPE_OFFICIAL);
        List<StUserTicket> list = userTicketMapper.selectByExample(example);

        ArrayList<StTicketDto> stTicketList = new ArrayList<>();
        for (StUserTicket ticket : list) {
            StTicketDto stTicketDto = new StTicketDto();
            BeanUtils.copyProperties(ticket, stTicketDto);
            Long userId = ticket.getUserId();
            User user = userMapper.queryUserByParam("", userId);
            if (null != user) {
                stTicketDto.setNick(user.getNick());
                stTicketDto.setAvatar(user.getAvatar());
            }
            stTicketList.add(stTicketDto);
        }
        return stTicketList;
    }


}
